package com.itmck.service;

import com.rabbitmq.client.Channel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.rabbit.connection.Connection;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;


@Slf4j
@Service
public class RabbbitMqServiceImpl implements RabbbitMqService {


    @Resource
    private RabbitTemplate rabbitTemplate;


    @Override
    public String createDlxExchange(String queueName, String dlxQueueName, String dlExchangeName) {


        ConnectionFactory connectionFactory = rabbitTemplate.getConnectionFactory();
        Connection connection = connectionFactory.createConnection();
        Channel channel = connection.createChannel(true);
        try {
            log.debug("创建交换机");
            channel.exchangeDeclare(dlExchangeName, "direct", true);//创建交换机
            Map<String, Object> args = new HashMap<>(2);
            args.put("x-dead-letter-exchange", dlExchangeName);
            args.put("x-dead-letter-routing-key", "KEY_R");
            channel.queueDeclare(queueName, true, false, false, args);//创建队列
            channel.queueBind(queueName, dlExchangeName, "DL_KEY", null);//将交换机和队列绑定


            channel.queueDeclare(dlxQueueName, true, false, false, null);
            channel.queueBind(dlxQueueName, dlExchangeName, "KEY_R");
            channel.close();
            return "创建死信队列成功";
        } catch (Exception e) {
            e.printStackTrace();
            return "创建死信队列失败";
        } finally {
            connection.close();
        }

    }
}
